<template>
	<van-search placeholder="去搜索更多感兴趣的新闻" disabled @click="searchNews"></van-search>
    <van-tabs
        v-model:active="activeTab"
        @change="onTabChange"
        :before-change="beforeChange"
        sticky
        animated
        swipeable
    >
        <van-tab v-for="item in tabList" :name="item" :key="item" :title="item">
            <van-pull-refresh v-model="state.refreshing" @refresh="onRefresh">
                <van-list
                    v-model:loading="state.loading"
                    :finished="state.finished"
                    finish-text="人家也是有底线的"
                    loading-text="火速加载中~"
                    @load="onLoad"
                >
                    <news-item
                        v-for="(item, index) in state.list"
                        :key="item.title"
                        :data="item"
                        @click="newsDetail(index)"
                    ></news-item>
                </van-list>
            </van-pull-refresh>
        </van-tab>
    </van-tabs>
</template>

<script>
import { defineComponent, reactive, ref } from '@vue/runtime-core'
import { getNewsChannel, getNewsList } from '@/utils/request'
import { useRouter} from 'vue-router'
import { useStore } from 'vuex'
import { setKey, removeKey } from '@/utils/helper'

export default defineComponent({
    setup() {
		const store = useStore()
        const activeTab = ref(0)
        const tabList = store.getters.getNewsChannel
		const limit = 10

        const state = reactive({
            list: [],
            loading: true,
            finished: false,
            refreshing: false,
			start: 0, //数据起始值, 等于 page
			ready: false
        })

		const resetParam = () => {
			state.list = []
			state.start = 0
			state.loading = true
			state.finished = false
		}

        const onLoad = () => {
            if (state.refreshing) {
                state.list = []
                state.refreshing = false
            }

			if (state.ready) {
				fetchNewsList()
			}
        }

        const onRefresh = () => {
            resetParam()

            onLoad()
        }

		const fetchNewsList = async () => {
			if (!state.loading) return false

			let { data } = await getNewsList({ channel: activeTab.value, start: state.start })
			let { list } = data

			list = list.filter(item=>item.content)
			state.list = state.list.concat(list)
			state.loading = false
			state.start += limit

			if (list.length < limit) {
				state.finished = true
			}
		}


        // 获取tab数据，应当缓存， todo
		if (tabList.length) {
			let homeIndex = store.getters.getHomeIndex
			activeTab.value = homeIndex

			let dataList = store.state.homepage

			if (dataList[homeIndex]) {
				console.log('cache');
				state.list = dataList[homeIndex]
				state.start = dataList.start
				state.loading = false
			}

			state.ready = true
		} else {
			getNewsChannel().then((res) => {
				tabList.value = res.data
				state.ready = true

				store.commit('updateNewsChannel', { list: res.data })
			})
		}

        const onTabChange = (name) => {
			resetParam()
			store.commit('updateHomeIndex', name)
			removeKey('homepage')
			fetchNewsList()
        }

        const beforeChange = () => {
			// 开启swipeable 时左右滑动不会触发。。
			// resetParam()
            return true
        }

		const newsDetail = (index) => {
			store.commit('updateHomepage', {
				[activeTab.value]: state.list,
				start: state.start
			})
			router.push(`/detail/${ activeTab.value }/${index}`)
		}

		const router = useRouter()
		const searchNews = () => {
			router.push('/search')
		}

        return {
            state,
            activeTab,
            tabList,
            onTabChange,
            beforeChange,
            onLoad,
            onRefresh,
			newsDetail,
			searchNews
        }
    },
})
</script>

<style>
.van-loading {
    text-align: center;
}
</style>
